// 游戏状态
const gameState = {
    selectedToy: 'all',
    timeMode: 60, // 默认1分钟
    score: 0,
    timeLeft: 60,
    isPlaying: false,
    toys: [],
    gameInterval: null,
    spawnTimeouts: [],
    audioContext: null // 音频上下文（单例）
};

// 玩具类型配置
const toyTypes = {
    all: ['🎾', '🐭', '🐟', '🐦', '🦋', '🪶', '🧶'],
    ball: ['🎾', '⚽', '🏀', '🎱'],
    mouse: ['🐭', '🐀'],
    fish: ['🐟', '🐠', '🐡'],
    bird: ['🐦', '🐤', '🐥'],
    butterfly: ['🦋', '🦟'],
    feather: ['🪶', '🎋'],
    yarn: ['🧶', '🎀']
};

// DOM 元素
const menuScreen = document.getElementById('menu-screen');
const gameScreen = document.getElementById('game-screen');
const gameoverScreen = document.getElementById('gameover-screen');
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');
const playBtn = document.getElementById('play-btn');
const replayBtn = document.getElementById('replay-btn');
const backMenuBtn = document.getElementById('back-menu-btn');
const menuBtn = document.getElementById('menu-btn');
const toyBtns = document.querySelectorAll('.toy-btn');
const timeBtns = document.querySelectorAll('.time-btn');
const pawIndicator = document.getElementById('paw-indicator');

// 玩具对象类
class Toy {
    constructor(canvas) {
        this.emoji = this.getRandomEmoji();
        this.size = Math.random() * 40 + 60; // 60-100px
        this.x = Math.random() * (canvas.width - this.size);
        this.y = Math.random() * (canvas.height - this.size);
        
        // 随机速度和方向
        const speed = Math.random() * 3 + 2;
        const angle = Math.random() * Math.PI * 2;
        this.vx = Math.cos(angle) * speed;
        this.vy = Math.sin(angle) * speed;
        
        // 旋转
        this.rotation = 0;
        this.rotationSpeed = (Math.random() - 0.5) * 0.1;
        
        // 闪烁效果
        this.sparkle = Math.random() > 0.5;
    }
    
    getRandomEmoji() {
        const emojis = toyTypes[gameState.selectedToy];
        return emojis[Math.floor(Math.random() * emojis.length)];
    }
    
    update(canvas) {
        this.x += this.vx;
        this.y += this.vy;
        this.rotation += this.rotationSpeed;
        
        // 边界反弹
        if (this.x <= 0 || this.x >= canvas.width - this.size) {
            this.vx *= -1;
            this.x = Math.max(0, Math.min(canvas.width - this.size, this.x));
        }
        if (this.y <= 0 || this.y >= canvas.height - this.size) {
            this.vy *= -1;
            this.y = Math.max(0, Math.min(canvas.height - this.size, this.y));
        }
    }
    
    draw(ctx) {
        ctx.save();
        ctx.translate(this.x + this.size / 2, this.y + this.size / 2);
        ctx.rotate(this.rotation);
        
        // 闪烁光晕
        if (this.sparkle && Math.random() > 0.7) {
            ctx.shadowColor = '#ffff00';
            ctx.shadowBlur = 20;
        }
        
        ctx.font = `${this.size}px Arial`;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(this.emoji, 0, 0);
        
        ctx.restore();
    }
    
    isClicked(x, y) {
        const centerX = this.x + this.size / 2;
        const centerY = this.y + this.size / 2;
        const distance = Math.sqrt((x - centerX) ** 2 + (y - centerY) ** 2);
        return distance < this.size / 2;
    }
}

// 初始化
function init() {
    resizeCanvas();
    window.addEventListener('resize', resizeCanvas);
    
    // 玩具选择
    toyBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            toyBtns.forEach(b => b.classList.remove('selected'));
            btn.classList.add('selected');
            gameState.selectedToy = btn.dataset.toy;
        });
    });
    
    // 默认选中第一个
    toyBtns[0].classList.add('selected');
    
    // 时间模式选择
    timeBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            timeBtns.forEach(b => b.classList.remove('selected'));
            btn.classList.add('selected');
            const timeValue = btn.dataset.time;
            gameState.timeMode = timeValue === 'unlimited' ? 'unlimited' : parseInt(timeValue);
        });
    });
    
    // 默认选中1分钟
    timeBtns[0].classList.add('selected');
    
    // 按钮事件
    playBtn.addEventListener('click', startGame);
    replayBtn.addEventListener('click', startGame);
    backMenuBtn.addEventListener('click', showMenu);
    menuBtn.addEventListener('click', () => {
        if (gameState.timeMode === 'unlimited') {
            // 不计时模式下，点击菜单按钮时显示结束界面
            endGame();
        } else {
            stopGame();
            showMenu();
        }
    });
    
    // 游戏交互
    canvas.addEventListener('mousedown', handleInteraction);
    canvas.addEventListener('touchstart', handleInteraction);
    canvas.addEventListener('mousemove', handleMouseMove);
    canvas.addEventListener('touchmove', handleTouchMove);
}

function resizeCanvas() {
    const header = document.querySelector('.game-header');
    const headerHeight = header ? header.offsetHeight : 0;
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight - headerHeight;
}

function showMenu() {
    menuScreen.classList.add('active');
    gameScreen.classList.remove('active');
    gameoverScreen.classList.remove('active');
}

function startGame() {
    gameState.score = 0;
    gameState.timeLeft = gameState.timeMode === 'unlimited' ? 0 : gameState.timeMode;
    gameState.isPlaying = true;
    gameState.toys = [];
    
    menuScreen.classList.remove('active');
    gameScreen.classList.add('active');
    gameoverScreen.classList.remove('active');
    
    resizeCanvas();
    updateUI();
    
    // 初始生成玩具
    for (let i = 0; i < 3; i++) {
        gameState.toys.push(new Toy(canvas));
    }
    
    // 游戏循环
    gameState.gameInterval = setInterval(gameLoop, 1000 / 60);
    
    // 开始随机生成玩具
    scheduleNextToy();
    
    // 倒计时（仅在非不计时模式下）
    if (gameState.timeMode !== 'unlimited') {
        const timerInterval = setInterval(() => {
            if (!gameState.isPlaying) {
                clearInterval(timerInterval);
                return;
            }
            
            gameState.timeLeft--;
            updateUI();
            
            if (gameState.timeLeft <= 0) {
                clearInterval(timerInterval);
                endGame();
            }
        }, 1000);
    } else {
        // 不计时模式：计数向上增长
        const timerInterval = setInterval(() => {
            if (!gameState.isPlaying) {
                clearInterval(timerInterval);
                return;
            }
            
            gameState.timeLeft++;
            updateUI();
        }, 1000);
    }
}

function stopGame() {
    gameState.isPlaying = false;
    if (gameState.gameInterval) clearInterval(gameState.gameInterval);
    
    // 清除所有待生成的玩具定时器
    gameState.spawnTimeouts.forEach(timeout => clearTimeout(timeout));
    gameState.spawnTimeouts = [];
}

// 随机间隔生成玩具（2-3秒）
function scheduleNextToy() {
    if (!gameState.isPlaying) return;
    
    const randomDelay = Math.random() * 1000 + 2000; // 2000-3000ms
    
    const timeout = setTimeout(() => {
        if (gameState.isPlaying && gameState.toys.length < 5) {
            gameState.toys.push(new Toy(canvas));
        }
        scheduleNextToy(); // 继续调度下一个
    }, randomDelay);
    
    gameState.spawnTimeouts.push(timeout);
}

function endGame() {
    stopGame();
    
    // 显示结果
    document.getElementById('final-score').textContent = gameState.score;
    
    // 显示游戏时长信息
    const playTimeInfo = document.getElementById('play-time-info');
    if (gameState.timeMode === 'unlimited') {
        const minutes = Math.floor(gameState.timeLeft / 60);
        const seconds = gameState.timeLeft % 60;
        playTimeInfo.textContent = `游戏时长：${minutes}分${seconds}秒`;
        playTimeInfo.style.display = 'block';
    } else {
        playTimeInfo.style.display = 'none';
    }
    
    // 根据分数显示不同的猫咪表情
    const catReaction = document.getElementById('cat-reaction');
    if (gameState.score >= 50) {
        catReaction.textContent = '😻';
    } else if (gameState.score >= 30) {
        catReaction.textContent = '😸';
    } else if (gameState.score >= 10) {
        catReaction.textContent = '😺';
    } else {
        catReaction.textContent = '😿';
    }
    
    gameScreen.classList.remove('active');
    gameoverScreen.classList.add('active');
}

function gameLoop() {
    if (!gameState.isPlaying) return;
    
    // 清空画布
    ctx.fillStyle = '#5a3e2b';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 绘制纹理背景
    drawBackground();
    
    // 更新和绘制玩具
    gameState.toys.forEach(toy => {
        toy.update(canvas);
        toy.draw(ctx);
    });
}

function drawBackground() {
    // 简单的地面纹理
    ctx.fillStyle = '#4a2e1b';
    for (let i = 0; i < 50; i++) {
        const x = Math.random() * canvas.width;
        const y = Math.random() * canvas.height;
        ctx.fillRect(x, y, 2, 2);
    }
}

function handleInteraction(e) {
    e.preventDefault();
    if (!gameState.isPlaying) return;
    
    const rect = canvas.getBoundingClientRect();
    const touches = e.touches || [e];
    
    for (let touch of touches) {
        const x = (touch.clientX || touch.pageX) - rect.left;
        const y = (touch.clientY || touch.pageY) - rect.top;
        
        // 检测是否点击到玩具
        for (let i = gameState.toys.length - 1; i >= 0; i--) {
            if (gameState.toys[i].isClicked(x, y)) {
                // 抓到了！
                gameState.score++;
                updateUI();
                
                // 移除玩具
                gameState.toys.splice(i, 1);
                
                // 随机延迟后添加新玩具（2-3秒）
                const randomDelay = Math.random() * 1000 + 2000;
                const timeout = setTimeout(() => {
                    if (gameState.isPlaying && gameState.toys.length < 5) {
                        gameState.toys.push(new Toy(canvas));
                    }
                }, randomDelay);
                gameState.spawnTimeouts.push(timeout);
                
                // 触摸效果
                createTouchEffect(x, y);
                
                // 音效（如果需要可以添加）
                playSound();
                
                break;
            }
        }
    }
}

function handleMouseMove(e) {
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    pawIndicator.style.left = x + 'px';
    pawIndicator.style.top = y + rect.top + 'px';
    pawIndicator.style.display = 'block';
}

function handleTouchMove(e) {
    e.preventDefault();
    if (e.touches.length > 0) {
        const rect = canvas.getBoundingClientRect();
        const x = e.touches[0].clientX - rect.left;
        const y = e.touches[0].clientY;
        
        pawIndicator.style.left = x + 'px';
        pawIndicator.style.top = y + 'px';
        pawIndicator.style.display = 'block';
    }
}

function createTouchEffect(x, y) {
    const effect = document.createElement('div');
    effect.className = 'touch-effect';
    effect.style.left = x + 'px';
    effect.style.top = y + 'px';
    effect.style.width = '50px';
    effect.style.height = '50px';
    effect.style.position = 'absolute';
    
    canvas.parentElement.appendChild(effect);
    
    setTimeout(() => {
        effect.remove();
    }, 600);
}

function playSound() {
    try {
        // 初始化音频上下文（单例模式，避免重复创建）
        if (!gameState.audioContext) {
            // 兼容不同浏览器的前缀
            const AudioContext = window.AudioContext || window.webkitAudioContext;
            if (!AudioContext) {
                console.warn('此浏览器不支持 Web Audio API');
                return;
            }
            gameState.audioContext = new AudioContext();
        }
        
        const audioContext = gameState.audioContext;
        
        // 如果 AudioContext 被暂停（某些移动浏览器会这样），尝试恢复
        if (audioContext.state === 'suspended') {
            audioContext.resume();
        }
        
        // 创建振荡器（生成声音）
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        // 连接节点：振荡器 → 增益控制 → 输出设备
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        // 设置音效参数 - 创建一个愉快的"抓到了"音效
        oscillator.type = 'sine'; // 正弦波，声音最柔和纯净
        oscillator.frequency.setValueAtTime(800, audioContext.currentTime); // 起始频率 800Hz
        oscillator.frequency.exponentialRampToValueAtTime(1200, audioContext.currentTime + 0.1); // 0.1秒内上升到1200Hz
        
        // 音量包络（ADSR 的简化版：快速淡出）
        gainNode.gain.setValueAtTime(0.3, audioContext.currentTime); // 起始音量 30%
        gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.15); // 0.15秒淡出
        
        // 播放音效
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 0.15); // 0.15秒后停止
    } catch (error) {
        // 静默处理错误，不影响游戏体验
        console.warn('音效播放失败:', error);
    }
}

function updateUI() {
    const timeElement = document.getElementById('time');
    if (gameState.timeMode === 'unlimited') {
        // 不计时模式：显示已玩时间
        const minutes = Math.floor(gameState.timeLeft / 60);
        const seconds = gameState.timeLeft % 60;
        timeElement.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
    } else {
        timeElement.textContent = gameState.timeLeft;
    }
    document.getElementById('score').textContent = gameState.score;
}

// 启动游戏
init();

